using System;
using System.Collections.Generic;
using System.Text;
using Prime31;
using UnityEngine;

public class EconomyVariableSettings
{
	private const char valueSeperator = ';';

	private const char arraySeperator = '|';

	private string prefix = string.Empty;

	public DateTime date;

	private string datePPKey = "date_";

	public Dictionary<int, List<float>> levelTimes;

	private string levelTimesPPKey = "levelTimes_";

	private string adLocationsPPKey = "adLocations_";

	private string adLocationsNamePPKey = "_name";

	private string adLocationEnabledPPKey = "_enabled";

	private string adLocationCooldownPPKey = "_cooldown";

	private string adLocationDelayPPKey = "_delay";

	private string adLocationTypePPKey = "_type";

	private string adLocationLastDateShownPPKey = "_lastDate";

	public Dictionary<NotificationsManager.NotificationName, NotificationsManager.Notification> notifications;

	private string notificationsPPKey = "notifications_";

	private string notificationsNameJSONKey = "_name";

	private string notificationsCooldownsJSONKey = "_cooldowns";

	private string notificationsDailyLimitJSONKey = "_dailyLimit";

	private string notificationsRewardJSONKey = "_reward";

	public Dictionary<IAPManager.ProductType, string> productPrices;

	private string productPriceKeyPrefix = "productPrices_";

	private string livesForRecordPPKey = "livesForRecord";

	private string livesForRecordJSONKey = "livesForRecord";

	public int livesForRecord;

	public EconomyVariableSettings()
	{
	}

	public EconomyVariableSettings(string keyPrefix)
	{
		prefix = keyPrefix;
	}

	public void Reset()
	{
		date = default(DateTime);
		levelTimes = null;
		productPrices = null;
		notifications = null;
	}

	public string ToJson()
	{
		return SimpleJson.encode(this);
	}

	public bool LoadJson(string encodedJson, bool log = false)
	{
		date = default(DateTime);
		levelTimes = null;
		object obj;
		if (!SimpleJson.tryDeserializeObject(encodedJson, out obj))
		{
			if (log)
			{
				Debug.Log("Failed decoding json!");
			}
			return false;
		}
		Dictionary<string, object> dictionary = obj as Dictionary<string, object>;
		if (dictionary == null)
		{
			if (log)
			{
				Debug.Log("json response is null!");
			}
			return false;
		}
		if (dictionary.ContainsKey(datePPKey))
		{
			if (!DateTime.TryParse((string)dictionary[datePPKey], out date))
			{
				if (log)
				{
					Debug.Log("Could not parse date");
				}
				return false;
			}
			if (log)
			{
				Debug.Log("Decoding " + levelTimesPPKey);
			}
			if (!dictionary.ContainsKey(levelTimesPPKey))
			{
				if (log)
				{
					Debug.Log("Could not load " + levelTimesPPKey);
				}
				return false;
			}
			object obj2 = dictionary[levelTimesPPKey];
			Dictionary<string, object> dictionary2 = obj2 as Dictionary<string, object>;
			if (dictionary2 == null)
			{
				if (log)
				{
					Debug.Log("Could not load " + levelTimesPPKey);
				}
				return false;
			}
			levelTimes = new Dictionary<int, List<float>>();
			foreach (KeyValuePair<string, object> item in dictionary2)
			{
				int num = int.Parse(item.Key);
				List<object> list = item.Value as List<object>;
				List<float> list2 = new List<float>();
				foreach (object item2 in list)
				{
					list2.Add(float.Parse(item2.ToString()));
				}
				if (list2 == null)
				{
					if (log)
					{
						Debug.Log("no level times for " + num);
					}
					return false;
				}
				levelTimes.Add(num, list2);
			}
			if (log)
			{
				Debug.Log("Decoding " + adLocationsPPKey);
			}
			if (!dictionary.ContainsKey(adLocationsPPKey))
			{
				if (log)
				{
					Debug.Log("Could not load " + adLocationsPPKey);
				}
				return false;
			}
			obj2 = dictionary[adLocationsPPKey];
			if (log)
			{
				Debug.Log("Decoding " + notificationsPPKey);
			}
			if (!dictionary.ContainsKey(notificationsPPKey))
			{
				if (log)
				{
					Debug.Log("Could not load " + notificationsPPKey);
				}
				return false;
			}
			obj2 = dictionary[notificationsPPKey];
			if (!TryParseNotifications(obj2, out notifications, log))
			{
				if (log)
				{
					Debug.Log("Could not parse " + notificationsPPKey);
				}
				return false;
			}
			if (log)
			{
				Debug.Log("Decoding " + livesForRecordJSONKey);
			}
			if (!dictionary.ContainsKey(livesForRecordJSONKey))
			{
				if (log)
				{
					Debug.Log("Could not load " + livesForRecordJSONKey);
				}
				return false;
			}
			obj2 = dictionary[livesForRecordJSONKey];
			if (!int.TryParse(obj2.ToString(), out livesForRecord))
			{
				if (log)
				{
					Debug.Log("Could not parse " + livesForRecordJSONKey);
				}
				return false;
			}
			return true;
		}
		if (log)
		{
			Debug.Log("Could not parse date");
		}
		return false;
	}

	public static EconomyVariableSettings LoadFromJson(string keyPrefix, string encodedJson, bool log = false)
	{
		EconomyVariableSettings economyVariableSettings = new EconomyVariableSettings(keyPrefix);
		if (economyVariableSettings.LoadJson(encodedJson, log))
		{
			return economyVariableSettings;
		}
		return null;
	}

	public bool Overwrite(EconomyVariableSettings newSettings)
	{
		if (newSettings == null || this == newSettings)
		{
			return false;
		}
		int num = date.CompareTo(newSettings.date);
		if (num >= 0)
		{
			return false;
		}
		date = newSettings.date;
		if (newSettings.levelTimes != null)
		{
			levelTimes = new Dictionary<int, List<float>>(newSettings.levelTimes);
		}
		if (newSettings.productPrices != null)
		{
			productPrices = new Dictionary<IAPManager.ProductType, string>(newSettings.productPrices);
		}
		if (newSettings.notifications != null)
		{
			if (notifications == null)
			{
				notifications = new Dictionary<NotificationsManager.NotificationName, NotificationsManager.Notification>();
			}
			foreach (KeyValuePair<NotificationsManager.NotificationName, NotificationsManager.Notification> notification in newSettings.notifications)
			{
				if (notifications.ContainsKey(notification.Key))
				{
					notifications[notification.Key].Overwrite(notification.Value);
				}
				else
				{
					notifications.Add(notification.Key, notification.Value);
				}
			}
		}
		livesForRecord = newSettings.livesForRecord;
		return true;
	}

	public bool LoadFromPlayerPrefs(bool useDefaults = true)
	{
		string key = prefix + datePPKey;
		date = UserPrefs.getDate(key);
		if (date == default(DateTime) && !useDefaults)
		{
			return false;
		}
		LoadLevelTimes_CustomEncoding();
		LoadProductPrices();
		LoadNotifications();
		key = prefix + livesForRecordPPKey;
		livesForRecord = UserPrefs.getInt(key, EconomySettings.livesForRecord);
		return true;
	}

	private void LoadLevelTimes_CustomEncoding()
	{
		string key = prefix + levelTimesPPKey;
		string @string = UserPrefs.getString(key, string.Empty);
		if (levelTimes == null)
		{
			levelTimes = new Dictionary<int, List<float>>();
		}
		int levelsCount = Globals.levelsCount;
		int timesCountForEachLevel = EconomySettings.timesCountForEachLevel;
		if (@string == null || @string == string.Empty || @string == string.Empty)
		{
			for (int i = 0; i < levelsCount; i++)
			{
				List<float> list = new List<float>();
				for (int j = 0; j < timesCountForEachLevel; j++)
				{
					list.Add(EconomySettings.timesForLevel[i + 1][j]);
				}
				levelTimes.Add(i + 1, list);
			}
			return;
		}
		string[] array = @string.Split('|');
		if (array == null || array.Length <= 0)
		{
			return;
		}
		for (int k = 0; k < array.Length; k++)
		{
			string[] array2 = array[k].Split(';');
			if (array2 != null && array2.Length == 2)
			{
				int key2 = int.Parse(array2[0]);
				List<float> list2 = new List<float>();
				string[] array3 = array2[1].Split(',');
				for (int l = 0; l < array3.Length; l++)
				{
					list2.Add(int.Parse(array3[l]));
				}
				levelTimes.Add(key2, list2);
			}
		}
		for (int m = array.Length; m < Globals.levelsCount; m++)
		{
			List<float> list2 = new List<float>();
			for (int n = 0; n < timesCountForEachLevel; n++)
			{
				list2.Add(EconomySettings.timesForLevel[m + 1][n]);
			}
			levelTimes.Add(m + 1, list2);
		}
	}

	private void LoadProductPrices()
	{
		string empty = string.Empty;
		string empty2 = string.Empty;
		productPrices = new Dictionary<IAPManager.ProductType, string>();
		foreach (int value in Enum.GetValues(typeof(IAPManager.ProductType)))
		{
			if (value != 0)
			{
				empty = prefix + productPriceKeyPrefix + (IAPManager.ProductType)value;
				empty2 = ((!Economy.applicationVersionChanged) ? UserPrefs.getString(empty, IAPManager.GetDefaultFormattedPrice((IAPManager.ProductType)value)) : IAPManager.GetDefaultFormattedPrice((IAPManager.ProductType)value));
				productPrices.Add((IAPManager.ProductType)value, empty2);
			}
		}
	}
	private void LoadNotifications()
	{
		notifications = new Dictionary<NotificationsManager.NotificationName, NotificationsManager.Notification>();
		foreach (int value in Enum.GetValues(typeof(NotificationsManager.NotificationName)))
		{
			if (value == 0)
			{
				continue;
			}
			bool flag = true;
			string text = prefix + notificationsPPKey + (NotificationsManager.NotificationName)value;
			if (UserPrefs.HasKey(text))
			{
				string @string = UserPrefs.getString(text, string.Empty);
				if (!notifications.ContainsKey((NotificationsManager.NotificationName)value))
				{
					notifications.Add((NotificationsManager.NotificationName)value, new NotificationsManager.Notification());
				}
				else
				{
					Debug.Log("LoadNotifications: notification already exists for key: " + text);
				}
				if (notifications[(NotificationsManager.NotificationName)value].Decode(@string))
				{
					flag = false;
				}
				else
				{
					Debug.Log("LoadNotifications: notification decoding failed for key: " + text);
				}
			}
			if (flag)
			{
				if (!notifications.ContainsKey((NotificationsManager.NotificationName)value))
				{
					notifications.Add((NotificationsManager.NotificationName)value, NotificationsManager.defaultNotifications[(NotificationsManager.NotificationName)value]);
				}
				else
				{
					notifications[(NotificationsManager.NotificationName)value] = NotificationsManager.defaultNotifications[(NotificationsManager.NotificationName)value];
				}
				if (value == 1)
				{
					notifications[(NotificationsManager.NotificationName)value].lastCompleted = DateTime.UtcNow;
				}
			}
		}
	}

	public void SaveToPlayerPrefs()
	{
		string key = prefix + datePPKey;
		UserPrefs.setDate(key, date);
		SaveLevelTimes_CustomEncoding();
		SaveNotifications();
		SaveProductPrices();
		key = prefix + livesForRecordPPKey;
		UserPrefs.setInt(key, livesForRecord);
	}

	private void SaveLevelTimes()
	{
		if (levelTimes == null)
		{
			return;
		}
		StringBuilder stringBuilder = new StringBuilder();
		int num = 0;
		stringBuilder.Append(prefix);
		stringBuilder.Append(levelTimesPPKey);
		foreach (KeyValuePair<int, List<float>> levelTime in levelTimes)
		{
			num = stringBuilder.Length;
			stringBuilder.Append((levelTime.Key - 1).ToString());
			stringBuilder.Append("_");
			for (int i = 0; i < levelTime.Value.Count; i++)
			{
				stringBuilder.Append(i.ToString());
				UserPrefs.setFloat(stringBuilder.ToString(), levelTime.Value[i]);
				stringBuilder.Length -= i.ToString().Length;
			}
			stringBuilder.Length = num;
		}
	}

	private void SaveLevelTimes_CustomEncoding()
	{
		if (levelTimes == null || levelTimes.Count == 0)
		{
			return;
		}
		StringBuilder stringBuilder = new StringBuilder();
		foreach (KeyValuePair<int, List<float>> levelTime in levelTimes)
		{
			stringBuilder.Append(levelTime.Key.ToString());
			stringBuilder.Append(';');
			List<float> value = levelTime.Value;
			for (int i = 0; i < value.Count; i++)
			{
				stringBuilder.Append(value[i].ToString());
				stringBuilder.Append(",");
			}
			stringBuilder.Length--;
			stringBuilder.Append('|');
		}
		stringBuilder.Length--;
		string key = prefix + levelTimesPPKey;
		UserPrefs.setString(key, stringBuilder.ToString());
	}
	private void SaveNotifications()
	{
		if (notifications == null)
		{
			return;
		}
		foreach (KeyValuePair<NotificationsManager.NotificationName, NotificationsManager.Notification> notification in notifications)
		{
			string key = prefix + notificationsPPKey + notification.Key;
			string sValue = notification.Value.Encode();
			UserPrefs.setString(key, sValue);
		}
	}

	private void SaveProductPrices()
	{
		if (productPrices == null)
		{
			return;
		}
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append(prefix);
		stringBuilder.Append(productPriceKeyPrefix);
		int length = stringBuilder.Length;
		foreach (KeyValuePair<IAPManager.ProductType, string> productPrice in productPrices)
		{
			if (productPrice.Key != 0)
			{
				stringBuilder.Append(productPrice.Key.ToString());
				UserPrefs.setString(stringBuilder.ToString(), productPrice.Value);
				stringBuilder.Length = length;
			}
		}
	}

	public void DeleteFromPlayerPrefs()
	{
		int levelsCount = Globals.levelsCount;
		int timesCountForEachLevel = EconomySettings.timesCountForEachLevel;
		string key = prefix + datePPKey;
		UserPrefs.DeleteKey(key);
		for (int i = 0; i < levelsCount; i++)
		{
			for (int j = 0; j < timesCountForEachLevel; j++)
			{
				key = prefix + datePPKey + i + "_" + j;
				UserPrefs.DeleteKey(key);
			}
		}
		key = prefix + levelTimesPPKey;
		UserPrefs.DeleteKey(key);
		if (productPrices != null)
		{
			foreach (KeyValuePair<IAPManager.ProductType, string> productPrice in productPrices)
			{
				if (productPrice.Key != 0)
				{
					key = prefix + productPriceKeyPrefix + productPrice.Key;
					UserPrefs.DeleteKey(key);
				}
			}
		}
		if (notifications != null)
		{
			foreach (KeyValuePair<NotificationsManager.NotificationName, NotificationsManager.Notification> notification in notifications)
			{
				key = prefix + notificationsPPKey + notification.Key;
				UserPrefs.DeleteKey(key);
			}
		}
		UserPrefs.Save();
	}

	public float[] GetTimesForLevel(int levelNumber)
	{
		if (levelTimes == null || !levelTimes.ContainsKey(levelNumber))
		{
			return null;
		}
		return levelTimes[levelNumber].ToArray();
	}
	private bool TryParseNotifications(object obj, out Dictionary<NotificationsManager.NotificationName, NotificationsManager.Notification> notifications, bool log = false)
	{
		notifications = new Dictionary<NotificationsManager.NotificationName, NotificationsManager.Notification>();
		if (obj == null)
		{
			if (log)
			{
				Debug.Log("Data is null");
			}
			notifications = null;
			return false;
		}
		List<object> list = obj as List<object>;
		if (list == null)
		{
			if (log)
			{
				Debug.Log("Could not cast to object list");
			}
			notifications = null;
			return false;
		}
		int num = 0;
		try
		{
			foreach (object item in list)
			{
				Dictionary<string, object> dictionary = item as Dictionary<string, object>;
				if (dictionary == null)
				{
					if (log)
					{
						Debug.Log("Could not cast to dict");
					}
					notifications = null;
					return false;
				}
				if (!dictionary.ContainsKey(notificationsNameJSONKey))
				{
					if (log)
					{
						Debug.Log("Could not find " + notificationsNameJSONKey + " key");
					}
					notifications = null;
					return false;
				}
				string text = (string)dictionary[notificationsNameJSONKey];
				NotificationsManager.NotificationName notificationName = NotificationsManager.NotificationName.None;
				foreach (int value in Enum.GetValues(typeof(NotificationsManager.NotificationName)))
				{
					if (text == ((NotificationsManager.NotificationName)value).ToString())
					{
						notificationName = (NotificationsManager.NotificationName)value;
						break;
					}
				}
				if (notificationName == NotificationsManager.NotificationName.None)
				{
					if (log)
					{
						Debug.Log(text + " is not a valid notification name");
					}
					notifications = null;
					return false;
				}
				if (!dictionary.ContainsKey(notificationsCooldownsJSONKey))
				{
					if (log)
					{
						Debug.Log("Could not find " + notificationsCooldownsJSONKey + " key");
					}
					notifications = null;
					return false;
				}
				List<object> list2 = dictionary[notificationsCooldownsJSONKey] as List<object>;
				if (list == null)
				{
					if (log)
					{
						Debug.Log("Could not cast " + notificationsCooldownsJSONKey + " to object list");
					}
					notifications = null;
					return false;
				}
				List<TimeSpan> list3 = new List<TimeSpan>();
				foreach (object item2 in list2)
				{
					TimeSpan timeSpan;
					if (!DecodeTimeSpan(item2 as string, out timeSpan))
					{
						if (log)
						{
							Debug.Log("Could not decode cooldown");
						}
						notifications = null;
						return false;
					}
					list3.Add(timeSpan);
				}
				if (!dictionary.ContainsKey(notificationsDailyLimitJSONKey))
				{
					notifications = null;
					return false;
				}
				int dailyLimit_ = int.Parse(dictionary[notificationsDailyLimitJSONKey].ToString());
				if (!dictionary.ContainsKey(notificationsRewardJSONKey))
				{
					notifications = null;
					return false;
				}
				int reward_ = int.Parse(dictionary[notificationsRewardJSONKey].ToString());
				if (!notifications.ContainsKey(notificationName))
				{
					notifications.Add(notificationName, new NotificationsManager.Notification(notificationName, list3, dailyLimit_, reward_));
				}
				else
				{
					notifications[notificationName] = new NotificationsManager.Notification(notificationName, list3, dailyLimit_, reward_);
				}
				num++;
			}
		}
		catch (Exception ex)
		{
			if (log)
			{
				Debug.Log("Could not parse " + ex.Message);
			}
			notifications = null;
			return false;
		}
		if (log)
		{
			Debug.Log("Parsed " + num + " notifications settings");
		}
		return true;
	}

	private bool DecodeTimeSpan(string encoded, out TimeSpan timeSpan)
	{
		return Utils.DecodeTimeSpan(encoded, out timeSpan);
	}

	private string EncodeTimeSpan(TimeSpan timeSpan)
	{
		if (timeSpan != default(TimeSpan))
		{
			return Utils.EncodeTimeSpan(timeSpan);
		}
		return string.Empty;
	}

	private bool DecodeTimeSpanList(string encoded, out List<TimeSpan> timeSpanList)
	{
		return Utils.DecodeTimeSpanList(encoded, out timeSpanList);
	}

	private string EncodeTimeSpanList(List<TimeSpan> timeSpanList)
	{
		char separator = '|';
		return Utils.EncodeTimeSpanList(timeSpanList, separator);
	}
}
